<script setup>
	import { h, nextTick, ref } from 'vue'
	import { Empty } from 'ant-design-vue'
	import {
		DeleteOutlined,
		EditOutlined,
		EllipsisOutlined,
		PlusCircleOutlined,
		PlusOutlined
	} from '@ant-design/icons-vue'
	import datasetApi from '@/views/plugin/dashboard/api/datasetApi'
	import DatasetForm from './DatasetForm.vue'
	import IndicatorForm from '@/views/plugin/dashboard/view/data/components/dataset/indicatorForm.vue'
	import ApiIndicatorForm from '@/views/plugin/dashboard/view/data/components/dataset/ApiIndicatorForm.vue'

	const emit = defineEmits({ handleLeafAction: null })

	const props = defineProps({
		onDatasetSelect: {
			type: Function,
			required: true
		}
	})

	const datasetFormRef = ref(null)
	const indicatorFormRef = ref(null)
	const apiIndicatorFormRef = ref(null)
	const cardLoading = ref(true)
	const treeData = ref([])
	const showModal = ref(false)

	const searchValue = ref('')
	const onSelect = (keys, info) => {
		if (info.node.isLeaf) {
			emit('handleLeafAction', { action: 'config', node: info.node })
		}
	}

	const handleConfigSelect = (action, node) => {
		emit('handleLeafAction', { action, node })
	}

	const deleteIndicator = (params) => {
		datasetApi.deleteIndicator(params).then(() => {
			loadTreeData()
		})
	}

	// 判断是否为API连接器类型
	const isApiConnector = (dataset) => {
		if (!dataset || !dataset.datasetType) {
			return false
		}
		return ['LOCAL_API', 'EXTERNAL_API', 'HTTP'].includes(dataset.datasetType)
	}

	// 处理叶子节点的操作
	const handleLeafAction = (action, node) => {
		switch (action) {
			case 'config':
				// 处理配置操作
				handleConfigSelect(action, node)
				break
			case 'edit':
				// 处理配置操作
				indicatorFormRef.value.onOpen(node.parentData, node.data)
				break
			case 'copy':
				// 处理复制操作
				break
			case 'delete':
				// 处理删除操作
				deleteIndicator({ datasetId: node.parentData.id, indicatorId: node.key })
				break
		}
	}
	// 删除数据集
	const removeDataset = (record) => {
		let params = [
			{
				id: record.id
			}
		]
		datasetApi.delete(params).then(() => {
			loadTreeData()
		})
	}
	// 添加指标
	const addIndicator = (record) => {
		indicatorFormRef.value.onOpen(record)
	}
	// 处理父节点的操作
	const handleParentAction = (action, node) => {
		console.log('handleParentAction', action, node)
		switch (action) {
			case 'edit':
				// 处理编辑操作
				datasetFormRef.value.onOpen(node.data)
				break
			case 'delete':
				// 处理删除操作
				removeDataset(node.data)
				break
			case 'add':
				// 处理添加指标操作
				indicatorFormRef.value.onOpen(node.data)
				break
			case 'addApi':
				// 处理添加API指标操作
				apiIndicatorFormRef.value.onOpen(node.data)
				break
		}
	}

	// 加载左侧的树
	const loadTreeData = () => {
		datasetApi
			.page()
			.then((res) => {
				cardLoading.value = false
				if (res !== null) {
					// 清空现有树数据
					treeData.value = []
					nextTick(() => {
						res.records.forEach((item) => {
							const children = item.config?.indicators.map((indicator) => {
								return {
									title: indicator.name,
									key: indicator.id,
									isLeaf: true,
									data: indicator,
									parentData: item
								}
							})
							treeData.value.push({
								title: item.name,
								key: item.id,
								isLeaf: false,
								children: children,
								data: item
							})
						})
					})
				}
			})
			.finally(() => {
				cardLoading.value = false
			})
	}

	onMounted(() => {
		loadTreeData()
	})

	defineExpose({
		loadTreeData
	})
</script>

<template>
	<div class="w-64 p-6 overflow-auto bg-white flex flex-col flex-1">
		<div class="flex justify-between items-center mb-4">
			<div class="text-xl font-semibold">数据集</div>
			<a-button size="small" :icon="h(PlusOutlined)" @click="datasetFormRef.onOpen()" />
		</div>
		<a-input-search v-model:value="searchValue" style="margin-bottom: 8px" placeholder="搜索" />
		<a-empty v-if="!treeData.length" description="暂无数据集" />
		<a-directory-tree v-else :showIcon="false" multiple :treeData="treeData" @select="onSelect" defaultExpandAll>
			<template #title="{ title, key, isLeaf, dataRef }">
				<div class="flex items-center justify-between w-full pr-2">
					<span v-if="title.indexOf(searchValue) > -1">
						{{ title.substring(0, title.indexOf(searchValue)) }}
						<span style="color: #f50">{{ searchValue }}</span>
						{{ title.substring(title.indexOf(searchValue) + searchValue.length) }}
					</span>
					<span v-else>{{ title }}</span>
					<a-dropdown :trigger="['click']">
						<a-button size="small" @click.stop type="link">
							<EllipsisOutlined />
						</a-button>
						<template #overlay>
							<a-menu>
								<template v-if="isLeaf">
									<!--									<a-menu-item @click="handleLeafAction('config', dataRef)"> <SettingOutlined /> 配置 </a-menu-item>-->
									<a-menu-item @click="handleLeafAction('edit', dataRef)">
										<EditOutlined />
										编辑
									</a-menu-item>
									<!--									<a-menu-item @click="handleLeafAction('copy', { key, title, isLeaf })">-->
									<!--										<CopyOutlined /> 复制-->
									<!--									</a-menu-item>-->
									<a-popconfirm title="确定要删除吗？" @confirm="handleLeafAction('delete', dataRef)">
										<a-menu-item>
											<DeleteOutlined />
											删除
										</a-menu-item>
									</a-popconfirm>
								</template>
								<template v-else>
									<a-menu-item @click="handleParentAction('edit', dataRef)">
										<EditOutlined />
										编辑
									</a-menu-item>
									<a-popconfirm title="确定要删除吗？" @confirm="handleParentAction('delete', dataRef)">
										<a-menu-item>
											<DeleteOutlined />
											删除
										</a-menu-item>
									</a-popconfirm>
									<!-- 根据连接器类型显示不同的添加菜单 -->
									<template v-if="isApiConnector(dataRef.data)">
										<a-menu-item @click="handleParentAction('addApi', dataRef)">
											<PlusCircleOutlined />
											选择接口
										</a-menu-item>
									</template>
									<template v-else>
										<a-menu-item @click="handleParentAction('add', dataRef)">
											<PlusCircleOutlined />
											添加指标
										</a-menu-item>
									</template>
								</template>
							</a-menu>
						</template>
					</a-dropdown>
				</div>
			</template>
		</a-directory-tree>
		<DatasetForm ref="datasetFormRef" @loadData="loadTreeData" />
		<IndicatorForm ref="indicatorFormRef" @loadData="loadTreeData" />
		<ApiIndicatorForm ref="apiIndicatorFormRef" @loadData="loadTreeData" />
	</div>
</template>
